﻿#region Header

// MS codename Velocity Distributed Cache Extensions.
// (c) 2009

#endregion


#region Usings

using System;

using Microsoft.Data.Caching;

using NUnit.Framework;

#endregion


namespace Caching.Extension.Core.Tests.Utils
{
    public class CacheTestBase : AssertionHelper
    {
        protected const string Region = "tests";
        protected const string DefaultRegion = null;

        private DataCache m_cache;
        private DataCacheFactory m_factory;

        protected DataCacheFactory Factory
        {
            get { return m_factory; }
        }

        protected DataCache MsCache
        {
            get { return m_cache; }
        }


        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            m_factory = CreateCacheFactory("localhost", false);
            try
            {
                m_factory.GetDefaultCache().CreateRegion(Region, true);
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode != DataCacheErrorCode.RegionAlreadyExists)
                    throw;
            }
            PostFixtureSetUp();
        }


        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {
            PreFixtureTearDown();
            try
            {
                m_factory.GetDefaultCache().RemoveRegion(Region);
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode != DataCacheErrorCode.RegionDoesNotExist)
                    throw;
            }
            m_factory.Dispose();
            m_factory = null;
        }


        [SetUp]
        public void SetUp()
        {
            m_cache = GetCache(Factory);
            PostSetUp();
        }


        [TearDown]
        public void TearDown()
        {
            PreTearDown();
            m_cache = null;
        }


        protected static DataCacheFactory CreateCacheFactory(string cacheHost, bool localCache)
        {
            var servers = new DataCacheServerEndpoint[1];
            servers[0] = new DataCacheServerEndpoint(cacheHost, 22233, "DistributedCacheService");
            return new DataCacheFactory(servers, true, false, DataCacheLocalCacheSyncPolicy.TimeoutBased, 300, 5);
        }


        #region Hooks 

        protected virtual DataCache GetCache(DataCacheFactory factory)
        {
            return factory.GetDefaultCache();
        }


        protected virtual void PostFixtureSetUp()
        {
        }


        protected virtual void PreFixtureTearDown()
        {
        }


        protected virtual void PostSetUp()
        {
        }


        protected virtual void PreTearDown()
        {
        }

        #endregion Hooks


        protected static string NewKey()
        {
            return "key." + Guid.NewGuid().ToString("N");
        }
    }
}